package cn.stylefeng.guns.modular.location.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.location.entity.RealLocation;
import cn.stylefeng.guns.modular.location.excel.ExcelUtils;
import cn.stylefeng.guns.modular.location.model.params.RealLocationParam;
import cn.stylefeng.guns.modular.location.service.RealLocationService;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;

import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.openapi.sdk.service.DataExchangeService;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;


/**
 * 控制器
 *
 * @author lww
 * @Date 2023-12-19 10:32:19
 */
@Controller
@RequestMapping("/realLocation")
public class RealLocationController extends BaseController {

    private String PREFIX = "/realLocation";
    private  String PREFIX2 = "/location";
    @Autowired
    private RealLocationService realLocationService;

    @Autowired
    private UserService userService;

    /**
     * 跳转到主页面
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/realLocation.html";
    }
    /**
     * 车辆实时位置
     *
     * @author lww
     * @Date 2023-12-18
     */
    @RequestMapping("/location")
    public String location(Model model) {
        return PREFIX2 + "/hxStorageStock.html";
    }
    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel1")
    public String toimportExcel1(Model model) {
        return PREFIX2 + "/import.html";
    }
    /**
     * 批量删除接口
     */
    @RequestMapping("/btnRevoke")
    @ResponseBody
    public ResponseData btnRevoke(Integer[] ids) {
        for (Integer id : ids) {
            RealLocationParam param = new RealLocationParam();
            param.setId(id);
            this.realLocationService.delete(param);
        }
        return ResponseData.success();
    }
    /**
     * 导入excel
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public ResponseData importExcel(@RequestParam("file") MultipartFile file) {
        ResponseData data = new ResponseData();
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件不能为空");
        }
        try (Workbook workbook = getWorkbook(file)) {
            Sheet sheet = workbook.getSheetAt(0); // 获取第一个Sheet页

            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                if (row.getRowNum() == 0) {
                    continue;
                }
                User user = userService.getcurrentUser();

                // 读取每一行的数据
                String vno = row.getCell(0).getStringCellValue();
                //System.out.println(vno);

                Map <String, String> map = new HashMap <String, String>(3);
                map.put("cid","96c66565-162a-436a-b3ef-8db0da2c0222");
                map.put("srt","d42d62c9-130a-43fe-8ce3-f407c64208fa");//私钥用于SDK生成签名，不会在请求中传输
                String newStr = vno + "_2";
                //System.out.println(newStr);
                map.put("vnos", newStr);
                map.put("timeNearby", "30");
                String url = "https://zhiyunopenapi.95155.com/save/apis/transTimeManageV3";
                DataExchangeService des = new DataExchangeService(5000, 8000);
                //System.out.println("请求地址:" + url);
               // 通过 https 方式调用，此方法内部会使用私钥生成签名参数 sign,私钥不会发送
                String res = des.postHttps(url, map);
                //System.out.println("返回:" + res);
                JSONObject resultJson = JSONObject.parseObject(res);
                JSONObject jsonObject = new JSONObject(resultJson);

                // 从 JSONObject 中获取 result 对象
                JSONObject resultObject = jsonObject.getJSONObject("result");

                // 从 result 对象中获取 firstVcl 对象
                JSONObject firstVclObject = resultObject.getJSONObject("firstVcl");
                // 从 firstVcl 对象中获取 adr 的值
                String vnoValue = firstVclObject.getString("vno");
                String adrValue = firstVclObject.getString("adr");
                String provinceValue = firstVclObject.getString("province");
                String cityValue = firstVclObject.getString("city");
                String countryValue = firstVclObject.getString("country");
                String lonValue = firstVclObject.getString("lon");
                String latValue = firstVclObject.getString("lat");
                Long utcValue = firstVclObject.getLong("utc");
                Instant instant = Instant.ofEpochMilli(utcValue);
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String formattedDateTime = localDateTime.format(formatter);

                String spdValue = firstVclObject.getString("spd");
                String offlineStateValue = firstVclObject.getString("offlineState");
                String offlineTimeValue = firstVclObject.getString("offlineTime");

                RealLocationParam realLocationParam = new RealLocationParam();
                realLocationParam.setVno(vnoValue);
                realLocationParam.setAdr(adrValue);
                realLocationParam.setProvince(provinceValue);
                realLocationParam.setCity(cityValue);
                realLocationParam.setCountry(countryValue);
                realLocationParam.setUtc(formattedDateTime);
                realLocationParam.setLat(latValue);
                realLocationParam.setLon(lonValue);
                realLocationParam.setSpd(spdValue);
                realLocationParam.setOfflineState(offlineStateValue);
                realLocationParam.setOfflineTime(offlineTimeValue);
                realLocationParam.setAccount(user.getAccount());
                realLocationService.add(realLocationParam);

            }
            data.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  data;
    }

    private Workbook getWorkbook(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        File tempFile = File.createTempFile("temp", fileExtension);
        file.transferTo(tempFile);
        FileInputStream fis = new FileInputStream(tempFile);

        Workbook workbook;
        if (fileExtension.equals(".xlsx")) {
            workbook = new XSSFWorkbook(fis);
        } else if (fileExtension.equals(".xls")) {
            workbook = new HSSFWorkbook(fis);
        } else {
            throw new IllegalArgumentException("不支持的文件格式");
        }

        fis.close();
        tempFile.deleteOnExit();

        return workbook;
    }
    /**
     * 下载模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcel")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException {
        String path = "assets/excel/reallocation.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("车辆实时位置查询模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 新增页面
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/realLocation_add.html";
    }

    /**
     * 编辑页面
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/realLocation_edit.html";
    }

    /**
     * 新增接口
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(RealLocationParam realLocationParam) {
        this.realLocationService.add(realLocationParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(RealLocationParam realLocationParam) {
        this.realLocationService.update(realLocationParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(RealLocationParam realLocationParam) {
        this.realLocationService.delete(realLocationParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author lww
     * @Date 2023-12-19
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(RealLocationParam realLocationParam) {
        RealLocation detail = this.realLocationService.getById(realLocationParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author lww
     * @Date 2023-12-19
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(RealLocationParam realLocationParam,String condition,String startTime,String endTime  ) {
        if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
            realLocationParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
        } else if (startTime == null && endTime == null){
            realLocationParam.setTimeInterval("'"+ DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
        }
        User user = userService.getcurrentUser();
        realLocationParam.setAccount(user.getAccount());

        return this.realLocationService.findPageBySpec(realLocationParam,condition);
    }

}


